﻿using System;
using System.Drawing;

namespace QuickRunCore.Helper
{
    /// <summary>
    /// 获取文件图标类
    /// </summary>
    public class ICONHelper
    {

        [System.Runtime.InteropServices.DllImport("shell32.dll", EntryPoint = "ExtractIcon")]
        private static extern IntPtr ExtractIconA(IntPtr hInst, [System.Runtime.InteropServices.MarshalAs(
                 System.Runtime.InteropServices.UnmanagedType.LPStr)] string lpszExeFileName, int nIconIndex);
        private static IntPtr hInst;

        /// <summary>
        /// 获取文件图标个数
        /// </summary>
        /// <param name="FilePath">文件路径</param>
        /// <returns>图标数量</returns>
        public static int GetFileIconCount(string FilePath)
        {
            if (System.IO.File.Exists(FilePath) || System.IO.Directory.Exists(FilePath))
            {
                System.IntPtr hIcon;

                // 文件所含图标的总数
                hIcon = ExtractIconA(hInst, FilePath, -1);

                // 没取到的时候
                if (hIcon.Equals(IntPtr.Zero))
                {
                    // 取得跟文件相关的图标
                    return 0;
                }
                else
                {
                    // 图标的总数
                    return hIcon.ToInt32();
                }
            }
            return 0;
        }

        [System.Runtime.InteropServices.DllImport("shell32.dll")]
        private static extern int ExtractIconEx(string lpszFile, int niconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, int nIcons);


        /// <summary>
        /// 获取文件图标
        /// </summary>
        /// <param name="FilePath">文件路径</param>
        /// <param name="Index">图标序号，从0开始</param>
        /// <returns></returns>
        public static System.Drawing.Icon GetFileIcon(string FilePath, int Index)
        {
            
            return Icon.ExtractAssociatedIcon(FilePath);

            //int _iconCount = GetFileIconCount(FilePath);
            //if (_iconCount == 0 || _iconCount < Index + 1)
            //{
            //    return Icon.ExtractAssociatedIcon(FilePath);
            //}
            //else
            //{
               
            //    IntPtr[] largeIcons, smallIcons;  //存放大/小图标的指针数组
            //    largeIcons = new IntPtr[_iconCount];
            //    smallIcons = new IntPtr[_iconCount];
            //    //抽取所有的大小图标保存到largeIcons和smallIcons中 
            //    ExtractIconEx(FilePath, 0, largeIcons, smallIcons, _iconCount);
            //    return System.Drawing.Icon.FromHandle(largeIcons[Index]);
            //}
        }
    }
}
